<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>鼠标按下 拖动绘制矩形</title>
  <script src="./konva.min.7-2-5.js"></script>
  <style>
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
    }

    #container {
      width: 100vw;
      height: 100vh;
      background-color: #f0f0f0;
    }
  </style>
</head>

<body>
  <button id="h2">鼠标按下拖动绘制矩形 - 创建交互式图形</button>
  <hr>
  <div id="container"></div>
  <script>
    // 创建一个 Konva 舞台
    const stage = new Konva.Stage({
      container: 'container',
      width: window.innerWidth,
      height: window.innerHeight
    })

    // 创建一个图层
    const layer = new Konva.Layer()
    stage.add(layer)

    // 矩形初始位置和尺寸变量
    let rect, startX, startY

    // 监听鼠标按下事件
    stage.on('mousedown touchstart', (e) => {
      // 获取鼠标 / 触摸位置
      const pos = stage.getPointerPosition()
      startX = pos.x
      startY = pos.y

      // 创建一个新的矩形
      rect = new Konva.Rect({
        x: startX,
        y: startY,
        width: 0,
        height: 0,
        stroke: 'black',
        strokeWidth: 2,
        draggable: true
      })
      layer.add(rect)
    })

    // 监听鼠标移动事件
    stage.on('mousemove touchmove', (e) => {
      if (!rect) {
        return
      }
      // 获取当前鼠标 / 触摸位置
      const pos = stage.getPointerPosition()
      const width = pos.x - startX
      const height = pos.y - startY


      // 确保矩形大小最小为 10x10
      if (Math.abs(width) < 10) {
        width = 10 * Math.sign(width)
      }
      if (Math.abs(height) < 10) {
        height = 10 * Math.sign(height)
      }


      // 更新矩形尺寸
      rect.width(width)
      rect.height(height)
      layer.batchDraw()
    })

    // 监听鼠标抬起事件
    stage.on('mouseup touchend', (e) => {
      rect = null  // 重置矩形对象，表示绘制结束
    });
  </script>
</body>

</html>